from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
import traceback
from django.contrib.contenttypes.models import ContentType
from books.models import Publisher


from django.contrib.auth.forms import AuthenticationForm

from django.contrib.auth.models import  Permission

def register(request):


	login_form=AuthenticationForm()

	print  request.method
	if request.method=='GET':
		return render_to_response('login.html',{'login_form':login_form,})
	
	#try:
	  #  username = request.POST['username']
	    #password = request.POST['password']
	#    user = authenticate(username=username, password=password)
	login_form=AuthenticationForm(data=request.POST)
	print request.POST['username']
	if login_form.is_valid():
		redirect_to=request.POST.get("next")

		if not redirect_to  or ' ' in redirect_to:
			redirect_to='/books'

		login(request,login_form.get_user())
		print "user"
		print login_form.get_user()
	else:
		redirect_to='/register'


	#logout(request)

	print 'ahhaha'
	print redirect_to
	return HttpResponseRedirect(redirect_to)
"""
	except :
	    print 'here'
	    print traceback.print_exc()
	    user=None
    	if user is not None:
	  	print user.has_perm('can view publisher')
		print user.get_all_permissions()
	
		content_type = ContentType.objects.get_for_model(Publisher)
		permission = Permission.objects.get(content_type=content_type, codename='view_publisher')

		request.user.user_permissions.add(permission)



	  	print user.has_perm('can view publisher')
		res=str( user)
		login(request, user)
		# Redirect to a success page.
		return HttpResponseRedirect('books/')
    	else:
		res='no user to login'
		return HttpResponse(res)
		# Return an error message.
"""


def logout(request):
	#session=request.session.get('username',False)
	#if session:
	#	del request.session['username']
	from django.contrib.auth import logout
	logout(request)
	
	return HttpResponse('logout success')

